package com.gopay.cashier.web.controller;

import com.gopay.cashier.common.exception.WebException;
import com.gopay.cashier.service.impl.AntiPhishServiceImpl;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 反钓鱼- 图片验证码
 * 
 * @author zhanglei - 2012-12-25
 */
@Controller
public class AntiPhishVerifyCodeController extends BaseController {

    @Resource(name = "antiPhishService")
    private AntiPhishServiceImpl antiPhishService;


    @RequestMapping("/antiphish/verifycode.jpeg")
    public ModelAndView getVerifycode(HttpServletRequest request, HttpServletResponse response) {
        printRequest();
        try {
            setResponse(response);
            String gopayOrderId = request.getParameter(GOPAY_ORDER_ID);
            CpsGenMainOrder order = cpsGeneralMainOrderQueryDAO.find(CpsGenMainOrder.class,gopayOrderId);
            if(order == null)
                throw new WebException(ProcCodeConstants.PROC_CODE_100E5041);

            String[] imgParams = antiPhishService.getAntiPhishInfo(order);

            BufferedImage img = rcsAntiPhishingCheckService.generateVerifyCodeImage(imgParams[0], imgParams[1],
                    imgParams[2], imgParams[3], imgParams[4]);
            request.getSession().setAttribute(KEY_ANTIPHISH_VERIFYCODE, imgParams[0]);
            writeResponse(response, img);
        } catch (Exception e) {
            logger.error("生成反钓鱼图片验证码发生错误！", e);
        }
        return null;
    }

    /*public static byte[] bufferedImageToByteArray(BufferedImage img)
            throws ImageFormatException, IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
        encoder.encode(img);
        return os.toByteArray();
    }*/


    private void writeResponse(HttpServletResponse response, BufferedImage bi) throws IOException {
        ServletOutputStream os = response.getOutputStream();
        ByteArrayOutputStream out = null;
        try {

            out = new ByteArrayOutputStream();
            ImageIO.write(bi, "JPEG", out);

          //  ImageIO.write(bi, "JPEG", os);
           // byte[] pic = bufferedImageToByteArray(bi);
            os.write(out.toByteArray(), 0, out.toByteArray().length);
            os.flush();
            response.flushBuffer();
        } catch (Exception e) {
            throw  e;
        } finally {
            if (out != null) {
                out.close();
                out = null;
            }
            if (os != null) {
                os.close();
                os=null;
            }


        }
    }

    private void setResponse(HttpServletResponse response) {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
    }

}
